package de.justphil.tcg.tcgserver.websockets.util;

import java.io.IOException;

import net.jcip.annotations.ThreadSafe;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;

import static de.justphil.tcg.tcgserver.commons.logging.TCGLogging.*;
import de.justphil.tcg.tcgserver.commons.exceptions.TCGException;
import de.justphil.tcg.tcgserver.util.JsonObjectProcessor;
import de.justphil.tcg.tcgserver.commons.util.StringUtil;
import de.justphil.tcg.tcgserver.websockets.messages.MessageSubject;
import de.justphil.tcg.tcgserver.websockets.messages.TCGMessage;
import de.justphil.tcg.tcgserver.commons.i18n.Error;

@ThreadSafe
public class MessageParser {
	private static final Logger log = logger(MessageParser.class);
	private static final ObjectMapper mapper = JsonObjectProcessor.getJsonObjectMapper();
	
	public static TCGMessage parse(String data) throws TCGException {
		try {
			TCGMessage msg = mapper.readValue(data, TCGMessage.class);
			
			if ( msg == null || StringUtil.isNullOrEmpty(msg.getSubject()) ) {
				log.info("{} (1)", Error.CLIENT_ERROR_MALFORMED_WEBSOCKET_MESSAGE);
				throw new TCGException(Error.CLIENT_ERROR_MALFORMED_WEBSOCKET_MESSAGE);
			}
			
			if ( !MessageSubject.isSubject(msg.getSubject()) ) {
				log.info(Error.CLIENT_ERROR_UNKNOWN_WEBSOCKET_MESSAGE_SUBJECT);
				throw new TCGException(Error.CLIENT_ERROR_UNKNOWN_WEBSOCKET_MESSAGE_SUBJECT);
			}
			
			return msg;
		}
		catch (JsonParseException e) {
			log.info("{} (2)", Error.CLIENT_ERROR_MALFORMED_WEBSOCKET_MESSAGE);
			throw new TCGException(Error.CLIENT_ERROR_MALFORMED_WEBSOCKET_MESSAGE);
		}
		catch (JsonMappingException e) {
			e.printStackTrace();
			log.info("{} (3)", Error.CLIENT_ERROR_MALFORMED_WEBSOCKET_MESSAGE);
			throw new TCGException(Error.CLIENT_ERROR_MALFORMED_WEBSOCKET_MESSAGE);
		}
		catch (IOException e) {
			log.info("{} (4)", Error.CLIENT_ERROR_MALFORMED_WEBSOCKET_MESSAGE);
			throw new TCGException(Error.CLIENT_ERROR_MALFORMED_WEBSOCKET_MESSAGE);
		}
	}
}
